﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using YiSha.Enums;
using YiSha.Util.Model;

namespace YiSha.Basics
{
    /// <summary>
    /// 全局异常处理
    /// </summary>
    public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            if (context.Exception is NotImplementedException)
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
            }
            else
            {
                //控制器
                var controllerName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ControllerName;
                //方法
                var actionName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ActionName;
                var contexts = context.ActionDescriptor.DisplayName;
                var err = new RespResult
                {
                    MsgCode = MsgCode.ServiceException,
                    Msg = $"控制器：{controllerName} 中 {actionName} 方法报错，错误信息： " + context.Exception.Message
                };
                context.Result = new OkObjectResult(err);
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
            }
        }
    }
}
